package im.vinci.server.common.tmsg;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class TransactionMessageHolder {
    private static final Logger log = LoggerFactory.getLogger(TransactionMessageHolder.class);

    private static final ThreadLocal<TransactionMessageHolder> holder = new ThreadLocal<>();
    private final SingleDBMessageStore store;
    private final SingleDBTransactionManager manager;
    private List<ProducerMessage> queue;


    static void init(SingleDBMessageStore store, SingleDBTransactionManager manager) {
        TransactionMessageHolder old = holder.get();
        if (old != null) {
            log.error("ThreadLocal 泄露{}", old);
        }
        holder.set(new TransactionMessageHolder(store,manager));
    }

    public static boolean insertMessage(ProducerMessage message) {
        TransactionMessageHolder container = holder.get();
        if (container == null)
            return false;
        container.add(message);
        return true;
    }

    static List<ProducerMessage> clear() {
        TransactionMessageHolder container = holder.get();
        if (container == null)
            return null;
        holder.remove();
        return container.queue;
    }

    private TransactionMessageHolder(SingleDBMessageStore store,SingleDBTransactionManager manager) {
        this.store = store;
        this.manager = manager;
    }

    private void add(ProducerMessage message) {
        if (this.queue == null) {
            this.queue = Lists.newArrayListWithCapacity(2);
        }
        this.queue.add(message);
        this.store.insertNew(message);
    }
}